<?php
namespace frontend\models\download;

use Yii;
use yii\data\Pagination;
use common\components\Logs;
use frontend\models\download\User;
use frontend\models\download\Virtual;
use common\components\FileToken;

class Download extends \yii\db\ActiveRecord
{
    
    /**
     * 软件下载 软件数据库表
     */
    public static function tableName()
    {
        return 'edu_soft';
    }
    
    /**
     * 软件下载 查询软件相关课程
     */
    public function getCourse() {
        return (new \yii\db\Query())
        ->select(['course_id','course_name'])
        ->from('edu_course')
        ->where(['status'=>1])
        ->orderBy(['upd_time'=>SORT_DESC])
        ->limit(23)
        ->all();        
    }
    
    /**
     * 软件下载 查询软件相关分类
     */
    public function getCategory() {
        return (new \yii\db\Query())
        ->select(['softcate_id','softcate_name'])
        ->from('edu_softcate')
        ->where(['softcate_status'=>1])
        ->orderBy(['softcate_sort'=>SORT_DESC])
        ->all();        
    }
    
    /**
     * 软件下载 查询软件相关分页信息
     */
    public function getSoftinfo($course_id = 0,$cate_id = 0) { 
        
        //查询条件
        $where = $this->getWhere($course_id,$cate_id);
		
        
        //总条数
        $num = (new \yii\db\Query())->select(['edu_soft.soft_id'])
                                    ->from('edu_soft')
                                    ->leftJoin('edu_soft_course', 'edu_soft_course.soft_id = edu_soft.soft_id')
                                    ->leftJoin('edu_softcate', 'edu_softcate.softcate_id = edu_soft.softcate_id')
                                    ->where($where)
                                    ->distinct()
                                    ->all();
        //分业数据
        $model = (new \yii\db\Query());
        $pagination = new Pagination([
            'defaultPageSize' => 12,
            'totalCount' => count($num),
        ]);
        
        //查询结果
        $res = $model
         ->select([
            'edu_soft.soft_id','soft_name','soft_desc',
            'soft_down_url','soft_down_count',
            'soft_size','soft_points','soft_thumb',
            'softcate_name'
        ])
        ->from('edu_soft')
        ->leftJoin('edu_soft_course', 'edu_soft_course.soft_id = edu_soft.soft_id')
        ->leftJoin('edu_softcate', 'edu_softcate.softcate_id = edu_soft.softcate_id')
        ->orderBy('soft_updtime DESC')
        ->where($where)
        ->distinct()
        ->offset($pagination->offset)
        ->limit($pagination->limit)
        ->all();       
        
		if(!isset($where['edu_soft_course.course_id'])){
			$where['edu_soft_course.course_id']='';
		}

		if(!isset($where['edu_soft.softcate_id'])){
		  $where['edu_soft.softcate_id']='';
		}
        return [
                'lists'=>$res,
                'paging'=>$pagination,
                'course'=>$where['edu_soft_course.course_id'],
                'cate'=>$where['edu_soft.softcate_id']
               ];
    } 
    
    /**
     * 软件下载 分页条件拼接
     */
    public function getWhere($course_id = 0,$cate_id = 0) {        
        $session = Yii::$app->session;
        $session->open();
        
        if(Yii::$app->request->get('removecourse')){
            $session->remove('downloadcourse_id');
        }else if(Yii::$app->request->get('removecate')) {
            $session->remove('downloadcate_id');
        }
        
        $where = array();
        
        $course_id = $course_id?$course_id:$session->get('downloadcourse_id');
        if($course_id!=0){
            $where['edu_soft_course.course_id'] = $course_id;
            $session->set('downloadcourse_id',$course_id);
        }
        
        $cate_id = $cate_id?$cate_id:$session->get('downloadcate_id');
        if($cate_id!=0){
            $where['edu_soft.softcate_id'] = $cate_id;
            $session->set('downloadcate_id',$cate_id);
        }
        
        return $where;
    }
    
    /**
     * 获取软件相关的课程
     */
    public function getSoftcourse($id = 0) {
        return (new \yii\db\Query())
        ->select(['course_name'])
        ->from('edu_soft_course')
        ->innerJoin('edu_course', 'edu_course.course_id = edu_soft_course.course_id')
        ->where(['edu_soft_course.soft_id'=>$id])
        ->all();
    }
    
    /**
     * 软件下载
     */
    function downFile($soft_id)
    {   
        $session = Yii::$app->session;
        $session->open();
        //判断是否登录
        if(empty($session->has('user_id'))){
            return ['info' => '请先登录', 'data' => 0];
        }
        
        //取用户的积分
        $virtual = User::find()->select(['user_virtual','user_name'])->where(['user_id'=>$session->get('user_id')])->one();
        
        //取积分，下载路径，下载次数
        $arr = (new \yii\db\Query())
                ->select(['soft_down_count','soft_points','soft_name'])
                ->from('edu_soft')
                ->where(['soft_id'=>$soft_id])
                ->one();
        
        //判断积分是否足够
        if($arr['soft_points']>$virtual->user_virtual){
            return ['info' => '您的积分不足！', 'data' => 1];
        }else{
            $bloor = Yii::$app->request->post('bloor')?Yii::$app->request->post('bloor'):0;
        }
        
        //查询下载日志
        $info = (new \yii\db\Query())
        ->select(['log_id','log_addtime'])
        ->from('edu_user_log')
        ->where(['soft_id'=>$soft_id])
        ->andwhere(['>','log_addtime',strtotime(date('Y-m-01 00:00:00'))])
        ->one();  
       
        //提示操作将会扣除积分
       
        
        if(!empty($info)) {
            $endt = date('d',time()-$info['log_addtime']);
            $is_alow = Yii::$app->request->post('is_alow')?Yii::$app->request->post('is_alow'):0;
            if($endt<15&&!$is_alow){
                return ['info' => '购买此产品免费天数还剩'.(15-$endt).'天', 'data' => 3];
            }
        }else{            
              if(!$bloor) {
                return ['info' => '本次操作将会扣除相应的积分，请谨慎操作！', 'data' => 2];
              }            
        }
        
        //扣除用户积分
        if(empty($info)||$endt>15){
            $modvir = User::findOne($session->get('user_id'));
            $modvir->user_virtual = $virtual->user_virtual-$arr['soft_points'];
            $modvir->update();
        }
        
        //更新下载次数
        $mod = Download::findOne($soft_id);
        $mod->soft_down_count = $arr['soft_down_count']+1;
        $mod->update();
        
        //记录积分消费详情
        $virtable= new Virtual;
        $virtable -> user_id = $session->get('user_id');
        $virtable -> username = $virtual->user_name;
        $virtable -> virtual_num = $arr['soft_points'];
        $virtable -> vartual_detail = '本次购买-'.$arr['soft_name'].'-共消费了'.$arr['soft_points'].'积分';
        $virtable -> virtual_addtime = time();
        $virtable -> virtual_status = 2;
        $virtable -> virtual_serial = time().rand(111,999);
        $virtable -> save();
        
        //添加下载日志
        Logs::RecordUser(2,$session->get('user_id'),$virtable -> vartual_detail,$soft_id);
        
        return ['info' => '确认下载！', 'data' => 4];
    }
    
    /**
     * 打开窗体下载
     */
    public function downloadSoft($soft_id = 0) {
        
        //软件信息
        $arr = (new \yii\db\Query())
        ->select(['soft_down_url', 'soft_name'])
        ->from('edu_soft')
        ->where(['soft_id'=>$soft_id])
        ->one();
        //获取下载接口token
        $token = FileToken::getToken($arr['soft_down_url']);

        //打开下载窗口
        $ext = substr($arr['soft_down_url'],strripos($arr['soft_down_url'],'.'));
        //$date=date("Ymd-Him");
        header( "Content-type:  application/octet-stream ");
        header( "Accept-Ranges:  bytes ");
        header( "Content-Disposition:  attachment;  filename=".$arr['soft_name']."$ext");
        readfile('http://files.bwphp.com/file/soft/download/'.$token.'?path='.$arr['soft_down_url']);
    }



	/**
     * 软件下载 查询软件相关信息
     */
    static public function getSoft($soft) { 
        $model = (new \yii\db\Query());
        
        //查询结果
        return $model
         ->select([
            'edu_soft.soft_id','soft_name','soft_desc',
            'soft_down_url','soft_down_count',
            'soft_size','soft_points','soft_thumb',
            'softcate_name'
        ])
        ->from('edu_soft')
        ->leftJoin('edu_soft_course', 'edu_soft_course.soft_id = edu_soft.soft_id')
        ->leftJoin('edu_softcate', 'edu_softcate.softcate_id = edu_soft.softcate_id')
        ->orderBy('soft_updtime DESC')
        ->where("edu_soft.soft_id in (".substr($soft,1).")")
		//->groupby("edu_soft.soft_sort")
        ->distinct()
        ->limit(8)
        ->all();
    }
    
    
    
    
    
    
    
    
    
    
}

?>